//
//  WBNetWorkManager.swift
//  weibo
//
//  Created by iobit on 2017/06/27.
//  Copyright © 2017 zhuxu. All rights reserved.
//

import UIKit
import AFNetworking

/*
    使用HTTPS需在info.plist中添加
    App Transport Security Settings>Allow Arbitrary Loads
    设置为yes
 */


enum WBHTTPMethod {
    case GET
    case POST
}


/// 网络管理工具
class WBNetWorkManager: AFHTTPSessionManager {
   
    /// 单例设计
    /// 静态区，常量，闭包
    /// 在第一次访问时，执行闭包，并且将结果保存在 shared 常量中
    /// 可以在括号里添加() -> WBNetWorkManager in，也可以写为shared: WBNetWorkManager
    static let shared = { () -> WBNetWorkManager in 
       
        // 实例化对象
        let instance = WBNetWorkManager()
        // 设置响应反序列化支持的数据类型
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return instance
    }()
    
    // 用户账户的懒加载属性
    lazy var userAccount = WBUserAccount()
    
    // 用户登录标记，计算型属性
    var userLogon: Bool {
        return userAccount.access_token != nil
    }

    
    func tokenRequest(method: WBHTTPMethod = .GET, URLString: String, parameters: [String: Any]?, completion: @escaping (_ json: Any?, _ isSuccess:Bool)->()) {
        
        // 处理token
        // 1> 判断token是否为空
        guard let token = userAccount.access_token else {
            // 发送通知，用户登录
            print("没有 token，需要登录！")
            NotificationCenter.default.post(name: NSNotification.Name(WBUserShouldLoginNotification), object: nil)
            completion(nil, false)
            return
            
        }
        
        // 2> 判断字典是否存在
        var param = parameters
        if  parameters==nil {
            param = [String: Any]()
        }
        
        // 3> 设置字典参数
        param!["access_token"] = token
        
        //真正发起请求
        request(URLString: URLString, parameters: param!, completion: completion)
    }
    
 
    /// 封装AFN的GET/POST方法
    ///
    /// - Parameters:
    ///   - method: GET/POST方法，默认GET
    ///   - URLString: url
    ///   - parameters: 参数字典
    ///   - completion: 完成回调
    func request(method: WBHTTPMethod = .GET, URLString: String, parameters: [String: Any], completion: @escaping (_ json: Any?, _ isSuccess:Bool)->()) {
        
        let success = {(task: URLSessionDataTask, json: Any?) in
            completion(json, true)
        }
    
        let failure = {(task: URLSessionDataTask?, error: Error) in
            if (task?.response as? HTTPURLResponse)?.statusCode == 403 {
                print("登录过期，请重新登录")
                // 发送通知，用户重新登录（本方法不知道被谁调用，谁接收到通知，谁就做处理）
                NotificationCenter.default.post(name: NSNotification.Name(WBUserShouldLoginNotification), object: "token_expires")
            }
            print("网络请求错误\(error)")
            completion(nil, false)
        }

        if method == .GET {
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }else {
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }
}
